package com.example.k8s.hello.common.bean;

import com.example.k8s.hello.common.exception.ApiExEnum;
import com.example.k8s.hello.common.exception.BizException;
import com.example.k8s.hello.common.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.client.RestClientException;

import java.util.Objects;

public class RestResponse<T> {

    public static final String SUCCESS_CODE = "0";
    public static final String DEFAULT_ERROR_CODE = "1";

    public static final String SUCCESS_MSG = "success";

    public String code;
    public String msg;
    public T data;

    public RestResponse() {}

    public RestResponse(String code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public RestResponse(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public static RestResponse success(Object data) {
        return new RestResponse(SUCCESS_CODE, SUCCESS_MSG, data);
    }

    public static RestResponse error(String code, String msg) {
        return new RestResponse(code, msg);
    }

    public static RestResponse error(String msg) {
        return error(DEFAULT_ERROR_CODE, msg);
    }

    public static RestResponse error(ApiExEnum apiExEnum) {
        return error(apiExEnum.name(), apiExEnum.summary);
    }

    public static RestResponse error(BizException bizException) {
        return error(bizException.getCode(), bizException.getMessage());
    }
    public static RestResponse error(Exception ex) {
        String msg = "服务器处理异常，请联系管理员";

        return error(exMsg(ex, msg));
    }

    public static RestResponse error(ApiExEnum apiExEnum, RestClientException ex) {
        String msg = apiExEnum.summary;

        msg = exMsg(ex, msg);
        return error(apiExEnum.name(), exMsg(ex, msg));
    }

    public boolean success() {
        return Objects.equals(code, SUCCESS_CODE);
    }

    public String toJson() {
        return JsonUtils.toJsonString(this);
    }

    private static String exMsg(Exception ex, String msg) {
        if (!StringUtils.isEmpty(ex.getMessage())) {
            msg = ex.getMessage();
        } else if (ex.getCause() != null && !StringUtils.isEmpty(ex.getCause().getMessage())) {
            msg = ex.getCause().getMessage();
        }

        if (msg.length() > 100) {
            msg = msg.substring(0, 100);
        }
        return msg;
    }


}
